//File: /home/san/src/projects/sanfs/MediaChanger/DataStoreDriver/DataStoreFactory.cs created by san at 10:07 AM 5/28/2007
//
//

using System;
using System.Collections;

namespace SanFS.MediaChangerLibrary
{
	class DuplicateDataStoreTypeException : Exception
	{
		public DuplicateDataStoreTypeException(string str)
		{
			Console.WriteLine("{0} is already defined as a data store type",
				str);
		}
	}
	
	public class DataStoreFactory
	{
		private static Hashtable	mTable = new Hashtable();
		
		static DataStoreFactory()
		{
			RegisterDataStore(new XmlDataStoreDriver());
			RegisterDataStore(new MySqlDataStoreDriver());
		}
		
		public static void RegisterDataStore(IDataStore Ds)
		{
			//Console.WriteLine("RegisterDataStore(): Registering key '{0}'", Ds.Key);
			if(!mTable.ContainsKey(Ds.Key)) {
				mTable.Add(Ds.Key, Ds);
			}
			else {
				throw new DuplicateDataStoreTypeException(Ds.Key);
			}
		}
		
		/*
		 * Create the proper DataStore object given a URI.
		 * Format of the URI is:
		 * "ds:<datatstorekey>:<datastoreparameters>
		 * ds:xmldatastore:/tmp/datastore
		 */
		public static IDataStore CreateDataStore(string Uri)
		{
			Console.WriteLine(String.Format("Uri: {0}",Uri));
			if (!Uri.StartsWith("ds:"))
				throw new ArgumentException("Malformatted Uri", "Uri");
				
			string	[]tokens = Uri.Split(':');
			
			if (!mTable.ContainsKey(tokens[1]))
				throw new ArgumentException("Unknown Datastore type", "Uri");
			IDataStore	ds = (IDataStore) mTable[tokens[1]];
			
			return ds.CreateInstance(Uri);
		}
	}  // END CLASS
}  // END NAMESPACE
